package com.xyulu.controller.system;

import com.xyulu.entity.BlogCategoryEntity;
import com.xyulu.entity.common.Result;
import com.xyulu.entity.common.RoleConstant;
import com.xyulu.service.BlogCategoryService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @Author luming
 * @Date 2021/3/3
 * @Version 1.0
 */
@RestController
@RequiresRoles(RoleConstant.ROOT)
@RequestMapping("/system/category")
public class SysCategoryController {

    @Resource
    private BlogCategoryService categoryService;

    /**
     * 获取全部分类信息
     * @return
     */
    @GetMapping("/list")
    public Result categoryList(){
        ArrayList<Map> data = new ArrayList<>();
        HashMap<String,Object> tempData;
        List<BlogCategoryEntity> list = categoryService.list();
        for (BlogCategoryEntity entity : list) {
            tempData = new HashMap<>();
            tempData.put("id",entity.getId());
            tempData.put("name",entity.getCategoryName());
            tempData.put("describe",entity.getCategoryDesc());
            tempData.put("articleNum",entity.getTotalArticle());
            tempData.put("parentId",entity.getPid());
            data.add(tempData);
        }
        return new Result(200,"分类查找成功",data);
    }

    /**
     * 根据id获取分类信息
     * @param id
     * @return
     */
    @GetMapping("/getCategoryById")
    public Result getCategoryById(Integer id){
        BlogCategoryEntity category = categoryService.getById(id);
        return new Result(200,"查找成功",category);
    }

    /**
     * 删除/批量删除分类信息
     * @param ids
     * @return
     */
    @GetMapping("/deleteCategoryByIds")
    public Result deleteCategoryByIds(String ids){

        //删除逻辑有待优化 Todo
        String[] split = ids.split(",");
        List<String> target = new ArrayList<>();
        for (String id : split) {
            target.add(id);
        }
        categoryService.removeByIds(target);
        return new Result(200,"删除成功");
    }


    /**
     * 更新/插入 分类信息
     * @param category
     * @return
     */
    @PostMapping("/addOrUpdateCategory")
    public Result addOrUpdateCategory(@RequestBody BlogCategoryEntity category){
        category.setPid(0);
        boolean flag = false;
        try {
            flag = categoryService.saveOrUpdate(category);
        } catch (Exception e) {
            if (e.getMessage().indexOf("Duplicate entry") > 0) {
                return new Result(400,"分类名重复");
            }
            return new Result(400,"操作失败");
        }
        return new Result(200,"操作成功");
    }
}
